package io.yyxx.boot.util;

import io.yyxx.boot.business.entity.AuthTokenRequest;
import io.yyxx.boot.business.entity.AuthTokenResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@RequiredArgsConstructor
@Component
/**
 * 通过调用本方法获取 token即企业访问凭证
 */
public class CorpAuthApi {
    private final RestTemplate restTemplate = new RestTemplate();

    //从配置文件中获取URL
    @Value("${ali.url.token}")
    private String tokenUrl;

    //从配置文件中获取应用key和secret
    @Value("${ali.strip.appKey}")
    private String appKey;

    @Value("${ali.strip.appSecret}")
    private String appSecret;

    @Value("${ali.strip.corpId}")
    private String corpId;

    /**
     * 获取企业访问凭证
     *
     * @param request 认证请求参数
     * @param appKey  应用key (从请求示例看需要作为URL参数)
     */
    public AuthTokenResponse getCorpToken(AuthTokenRequest request, String appKey) {
        // 参数校验
        if (request.getType() == null || !Arrays.asList(0, 1).contains(request.getType())) {
            throw new IllegalArgumentException("企业类型参数不合法");
        }
        //原来isBlank方法，JDK8不可用
        if (request.getCorpId() == null || request.getCorpId().isEmpty()) {
            throw new IllegalArgumentException("企业ID不能为空");
        }

        // 构建查询参数
        Map<String, Object> params = new HashMap<>();
        params.put("app_key", appKey);
        params.put("type", request.getType());
        params.put("corp_id", request.getCorpId());
        if (request.getAppSecret() != null) {
            params.put("app_secret", request.getAppSecret());
        }

        // 发送请求
        ResponseEntity<AuthTokenResponse> response = restTemplate.exchange(
                tokenUrl + "?app_key={app_key}&type={type}&corp_id={corp_id}&app_secret={app_secret}",
                HttpMethod.GET,
                null,
                AuthTokenResponse.class,
                params
        );
        return response.getBody();
    }

    public String getToken() {

        AuthTokenRequest request = new AuthTokenRequest();
        // 设置请求参数，Type必须传0
        request.setType(0);
        request.setCorpId(corpId);
        request.setAppSecret(appSecret);
        // 调用上面getCorpToken发送请求
        AuthTokenResponse response = getCorpToken(request, appKey);
        // 处理返回结果
        if (response.getSuccess() && "SUCCESS".equals(response.getCode())) {
            log.info("获取Token成功：" + response.getModule().getToken());
            log.info("有效期：" + response.getModule().getExpire() + "毫秒");
        } else {
            log.error("获取Token失败：" + response.getMessage());
        }
        return response.getModule().getToken();
    }
}